import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:yurun_smartmerchants/generated/json/base/json_convert_content.dart';
import 'package:yurun_smartmerchants/global.dart';
import 'package:yurun_smartmerchants/models/qrcode_entity.dart';
import 'package:yurun_smartmerchants/models/qrcode_scan_entity.dart';
import 'package:yurun_smartmerchants/net/ApiInterface.dart';
import 'package:yurun_smartmerchants/net/NetUtil.dart';
import 'package:yurun_smartmerchants/page/staff_management.dart';
import 'package:yurun_smartmerchants/res/colours.dart';
import 'package:yurun_smartmerchants/routes/routes.dart';
import 'package:yurun_smartmerchants/utils/app_size.dart';
import 'package:yurun_smartmerchants/utils/loading_utils.dart';
import 'package:yurun_smartmerchants/view/qr_dialog.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yurun_smartmerchants/models/home_consumer_type_entity.dart';

class WorkSpace extends StatefulWidget {
  @override
  _WorkSpaceState createState() => _WorkSpaceState();
}

class _WorkSpaceState extends State<WorkSpace> {
  String scanResult = '';
  String merchantName = '';

  Future scan() async {
    try {
      var options = ScanOptions(
        strings: {
          "cancel": "取消",
          "flash_on": "闪光灯 开",
          "flash_off": "闪光灯 关",
        },
      );

      var result = await BarcodeScanner.scan(options: options);
      setState(() => scanResult = result.rawContent);
      if (scanResult.isNotEmpty) {
        _scanCodeCallback(scanResult);
      }
    } on PlatformException catch (e) {
      var result = ScanResult(
        type: ResultType.Error,
        format: BarcodeFormat.unknown,
      );

      if (e.code == BarcodeScanner.cameraAccessDenied) {
        setState(() {
          result.rawContent = '用户未打开相机权限!';
        });
      } else {
        result.rawContent = '未知错误: $e';
      }
      setState(() {
        scanResult = result.rawContent;
        if (scanResult.isNotEmpty) {
          showToast(scanResult);
        }
      });
    }
  }

//  Future qrScan() async {
//    // Native channel
//    const platform = const MethodChannel("flutter/bridge");
//    String result = "no";
//    try {
//      result = await platform.invokeMethod("qrScan");
//      showToast(result);
//    } on PlatformException catch (e) {
//      print(e.toString());
//    }
//  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _getConsumerType();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          color: Color(0xffefefef),
          child: Container(
              child: Column(children: <Widget>[
            Container(
              alignment: Alignment.bottomCenter,
              margin: EdgeInsets.only(bottom: AppSize.sp(20)),
              height: AppSize.height(126),
              child: Image.asset(
                'images/main_logo.png',
                width: AppSize.width(252),
                height: AppSize.height(52),
              ),
            ),
            Container(
              alignment: Alignment.bottomCenter,
              child: Column(
                children: <Widget>[
                  Container(
                    decoration: new BoxDecoration(
                        color: Colours.app_main,
                        borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(AppSize.sp(12)),
                            topRight: Radius.circular(AppSize.sp(12)))),
                    margin: EdgeInsets.only(
                        left: AppSize.sp(32), right: AppSize.sp(32)),
                    child: Flex(
                      direction: Axis.horizontal,
                      children: <Widget>[
                        Expanded(
                            flex: 1,
                            child: GestureDetector(
                              onTap: () {
                                _getQRCode();
                              },
                              child: Container(
                                height: AppSize.height(197),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Image.asset(
                                      'images/icon_identity_code.png',
                                      fit: BoxFit.cover,
                                    ),
                                    Padding(
                                        child: Text(
                                          '身份码',
                                          style: TextStyle(
                                              color: Colours.white,
                                              fontSize: 15),
                                        ),
                                        padding: EdgeInsets.only(
                                            top: AppSize.height(10)))
                                  ],
                                ),
                              ),
                            )),
                        Expanded(
                            flex: 1,
                            child: GestureDetector(
                              onTap: () {
                                showToast('我的钱包');
                              },
                              child: Container(
                                height: AppSize.height(197),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Image.asset(
                                      'images/main_money_package.png',
                                      fit: BoxFit.cover,
                                    ),
                                    Padding(
                                        child: Text(
                                          '我的钱包',
                                          style: TextStyle(
                                              color: Colours.white,
                                              fontSize: 15),
                                        ),
                                        padding: EdgeInsets.only(
                                            top: AppSize.height(10)))
                                  ],
                                ),
                              ),
                            )),
                        Expanded(
                            flex: 1,
                            child: GestureDetector(
                              onTap: () {
                                scan();
                              },
                              child: Container(
                                height: AppSize.height(197),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Image.asset(
                                      'images/icon_scan_code.png',
                                      fit: BoxFit.cover,
                                    ),
                                    Padding(
                                        child: Text(
                                          '扫码',
                                          style: TextStyle(
                                              color: Colours.white,
                                              fontSize: 15),
                                        ),
                                        padding: EdgeInsets.only(
                                            top: AppSize.height(10)))
                                  ],
                                ),
                              ),
                            ))
                      ],
                    ),
                  )
                ],
              ),
            ),
            Expanded(
              child: Container(
                child: ListView.builder(
                    itemBuilder: (context, index) {
                      if (index == 0) {
                        return getItemFirst(context);
                      } else {
                        return getItem(context, index);
                      }
                    },
                    itemCount: 5),
              ),
            )
          ]))),
    );
  }

  Widget getItemFirst(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          padding: EdgeInsets.only(
              top: AppSize.height(25), left: AppSize.height(30)),
          color: Colors.white,
          alignment: Alignment.topLeft,
          child: Text(
            '工具箱',
            style: TextStyle(
                color: Color(0xff313131),
                fontSize: 15,
                fontWeight: FontWeight.w700),
          ),
        ),
        Container(
          color: Colors.white,
          padding: EdgeInsets.only(top: AppSize.height(30)),
          child: Flex(
            direction: Axis.horizontal,
            children: <Widget>[
              Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(context, approach_administration_page);
                  },
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          'images/icon_jinchang_guanli.png',
                          fit: BoxFit.cover,
                        ),
                        Padding(
                          child: Text(
                            '进场管理',
                            style: TextStyle(
                                fontSize: 12, color: Color(0xff626262)),
                          ),
                          padding: EdgeInsets.only(top: AppSize.height(10)),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(context, tally_management_page);
                  },
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          'images/icon_lihuo_guanli.png',
                          fit: BoxFit.cover,
                        ),
                        Padding(
                          child: Text(
                            '理货管理',
                            style: TextStyle(
                                fontSize: 12, color: Color(0xff626262)),
                          ),
                          padding: EdgeInsets.only(top: AppSize.height(10)),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                    showToast('采购理货');
                  },
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          'images/main_purchase_tally.png',
                          fit: BoxFit.cover,
                        ),
                        Padding(
                          child: Text(
                            '采购理货',
                            style: TextStyle(
                                fontSize: 12, color: Color(0xff626262)),
                          ),
                          padding: EdgeInsets.only(top: AppSize.height(10)),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(context, inventory_management_page);
                  },
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          'images/icon_kucun_guanli.png',
                          fit: BoxFit.cover,
                        ),
                        Padding(
                          child: Text(
                            '库存管理',
                            style: TextStyle(
                                fontSize: 12, color: Color(0xff626262)),
                          ),
                          padding: EdgeInsets.only(top: AppSize.height(10)),
                        )
                      ],
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
        Container(
          color: Colors.white,
          padding: EdgeInsets.only(
              top: AppSize.height(30), bottom: AppSize.height(30)),
          child: Flex(
            direction: Axis.horizontal,
            children: <Widget>[
              Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                    showToast('订单管理');
                  },
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          'images/main_order_manage.png',
                          fit: BoxFit.cover,
                        ),
                        Padding(
                          child: Text(
                            '订单管理',
                            style: TextStyle(
                                fontSize: 12, color: Color(0xff626262)),
                          ),
                          padding: EdgeInsets.only(top: AppSize.height(10)),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                  Navigator.pushNamed(context, product_manage);
                  },
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          'images/icon_shangpin_guanli.png',
                          fit: BoxFit.cover,
                        ),
                        Padding(
                          child: Text(
                            '商品管理',
                            style: TextStyle(
                                fontSize: 12, color: Color(0xff626262)),
                          ),
                          padding: EdgeInsets.only(top: AppSize.height(10)),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                    showToast('销售台账');
                  },
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          'images/icon_xiaoshou_taizhang.png',
                          fit: BoxFit.cover,
                        ),
                        Padding(
                          child: Text(
                            '销售台账',
                            style: TextStyle(
                                fontSize: 12, color: Color(0xff626262)),
                          ),
                          padding: EdgeInsets.only(top: AppSize.height(10)),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(context, custom_administration);
                  },
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          'images/main_customer_manage.png',
                          fit: BoxFit.cover,
                        ),
                        Padding(
                          child: Text(
                            '客户管理',
                            style: TextStyle(
                                fontSize: 12, color: Color(0xff626262)),
                          ),
                          padding: EdgeInsets.only(top: AppSize.height(10)),
                        )
                      ],
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
        Container(
          color: Colors.white,
          padding: EdgeInsets.only(
              top: AppSize.height(30), bottom: AppSize.height(30)),
          child: Flex(
            direction: Axis.horizontal,
            children: <Widget>[
              Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                    Navigator.pushNamed(context, staff_management_page);
//                    Navigator.of(context).push(MaterialPageRoute(settings: RouteSettings(name: staff_management_page),builder: (context) => StaffManagementPage()));
                  },
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          'images/icon_yuangong_guanli.png',
                          fit: BoxFit.cover,
                        ),
                        Padding(
                          child: Text(
                            '员工管理',
                            style: TextStyle(
                                fontSize: 12, color: Color(0xff626262)),
                          ),
                          padding: EdgeInsets.only(top: AppSize.height(10)),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: GestureDetector(
                  onTap: () {
                    showToast('场内叫车');
                  },
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          'images/main_call_car.png',
                          fit: BoxFit.cover,
                        ),
                        Padding(
                          child: Text(
                            '场内叫车',
                            style: TextStyle(
                                fontSize: 12, color: Color(0xff626262)),
                          ),
                          padding: EdgeInsets.only(top: AppSize.height(10)),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(),
              ),
              Expanded(
                flex: 1,
                child: Container(),
              )
            ],
          ),
        ),
        Container(
          height: AppSize.height(88),
          color: Colours.white,
          alignment: Alignment.center,
          margin: EdgeInsets.only(top: AppSize.sp(20), bottom: AppSize.sp(1)),
          child: Row(
            children: <Widget>[
              Container(
                  margin: EdgeInsets.only(left: AppSize.sp(32)),
                  child: Text("最新订单",
                      style: TextStyle(
                          fontSize: AppSize.sp(30),
                          fontWeight: FontWeight.w700,
                          color: Colours.color_434343))),
              Spacer(),
              GestureDetector(
                onTap: (){
                  showToast("更多");
                },
                child:Container(
                  height: AppSize.height(88),
                  child: Row(
                    children: <Widget>[
                      Text("更多",
                          style: TextStyle(
                              color: Colours.color_c7c7c7, fontSize: AppSize.sp(28))),
                      Container(
                          margin: EdgeInsets.only(
                              left: AppSize.sp(10), right: AppSize.sp(32)),
                          child: Icon(
                            Icons.arrow_forward_ios,
                            color: Colours.color_c7c7c7,
                            size: AppSize.sp(28),
                            textDirection: TextDirection.ltr,
                          ))
                    ],
                  ),
                ),)
            ],
          ),
        ),
      ],
    );
  }

  Widget getItem(BuildContext context, int index) {
    return GestureDetector(
      onTap: () {
        showToast("点击详情");
      },
      child: Container(
          color: Colours.white,
          height: AppSize.height(270),
          alignment: Alignment.center,
          margin: EdgeInsets.only(bottom: AppSize.sp(1)),
          child: Column(children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(
                      left: AppSize.sp(32), top: AppSize.sp(32)),
                  child: Text(
                    "订单 123456",
                    style: TextStyle(fontSize: AppSize.sp(30)),
                  ),
                ),
                Container(
                  width: AppSize.width(104),
                  height: AppSize.height(30),
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(
                      left: AppSize.sp(26), top: AppSize.sp(32)),
                  decoration: new BoxDecoration(
                      border: Border.all(width: 1, color: Colours.blue_1),
                      borderRadius:
                          BorderRadius.all(Radius.circular(AppSize.sp(4)))),
                  child: Text(
                    "线上订单",
                    style: TextStyle(
                        fontSize: AppSize.sp(22), color: Colours.blue_1),
                  ),
                ),
                Spacer(),
                Container(
                  margin: EdgeInsets.only(
                      right: AppSize.sp(32), top: AppSize.sp(32)),
                  child: Text(
                    "2020-06-15 13 : 45",
                    style: TextStyle(
                        fontSize: AppSize.sp(24), color: Colours.color_c7c7c7),
                  ),
                )
              ],
            ),
            Row(
              children: <Widget>[
                Container(
                  width: AppSize.sp(30),
                  height: AppSize.sp(30),
                  margin: EdgeInsets.only(
                      left: AppSize.sp(32), top: AppSize.sp(20)),
                  child: CircleAvatar(
                    backgroundColor: Colours.color_adb0ba,
                    child: Container(
                      child: Icon(
                        Icons.person,
                        color: Colours.white,
                        size: AppSize.sp(26),
                      ),
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                      left: AppSize.sp(14), top: AppSize.sp(20)),
                  child: Text(
                    "张先生",
                    style: TextStyle(fontSize: AppSize.sp(28)),
                  ),
                ),
                Container(
                  width: AppSize.width(1),
                  height: AppSize.height(28),
                  color: Colours.color_dcdcdc,
                  margin: EdgeInsets.only(
                      left: AppSize.sp(20), top: AppSize.sp(20)),
                ),
                Container(
                  margin: EdgeInsets.only(
                      left: AppSize.sp(20), top: AppSize.sp(20)),
                  child: Icon(
                    Icons.phone,
                    color: Colours.color_adb0ba,
                    size: AppSize.sp(28),
                  ),
                ),
                Spacer(),
                Container(
                  margin: EdgeInsets.only(
                      right: AppSize.sp(32), top: AppSize.sp(20)),
                  child: Text(
                    "待卖方确认",
                    style: TextStyle(
                        fontSize: AppSize.sp(24), color: Colours.color_FF7900),
                  ),
                )
              ],
            ),
            Row(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(
                      left: AppSize.sp(32), top: AppSize.sp(20)),
                  child: Text(
                    "商品名称: 青菜",
                    style: TextStyle(
                        fontSize: AppSize.sp(24), color: Colours.color_898989),
                  ),
                ),
                Spacer(),
                Container(
                  margin: EdgeInsets.only(
                      right: AppSize.sp(32), top: AppSize.sp(20)),
                  child: Text(
                    "1220元",
                    style: TextStyle(
                        fontSize: AppSize.sp(28), color: Colours.color_313131),
                  ),
                )
              ],
            ),
            Row(
              children: <Widget>[
                Spacer(),
                GestureDetector(
                  onTap: () {
                    showToast("取消订单");
                  },
                  child: Container(
                    width: AppSize.width(160),
                    height: AppSize.height(50),
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(
                        right: AppSize.sp(20), top: AppSize.sp(20)),
                    decoration: new BoxDecoration(
                        border:
                            Border.all(width: 1, color: Colours.color_dcdcdc),
                        borderRadius:
                            BorderRadius.all(Radius.circular(AppSize.sp(24)))),
                    child: Text(
                      "取消订单",
                      style: TextStyle(
                          fontSize: AppSize.sp(28), color: Colours.green_62),
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    showToast("收款");
                  },
                  child: Container(
                    width: AppSize.width(160),
                    height: AppSize.height(50),
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(
                        right: AppSize.sp(32), top: AppSize.sp(20)),
                    decoration: new BoxDecoration(
                        border:
                            Border.all(width: 1, color: Colours.color_dd4b39),
                        borderRadius:
                            BorderRadius.all(Radius.circular(AppSize.sp(24)))),
                    child: Text(
                      "收款",
                      style: TextStyle(
                          fontSize: AppSize.sp(28),
                          color: Colours.color_dd4b39),
                    ),
                  ),
                ),
              ],
            ),
          ])),
    );
  }

  void _getConsumerType() {
    LoadingUtil.showLoading(context, tip: '加载中...');
    ApiInterface.homeConsumerType().then((value) {
      HomeConsumerTypeEntity homeConsumerTypeEntity =
          JsonConvert.fromJsonAsT<HomeConsumerTypeEntity>(value);
      Global.prefs.setString(
          Global.consumer_id, homeConsumerTypeEntity.consumerId.toString());
      Global.prefs.setBool(Global.owned, homeConsumerTypeEntity.owned);
      String name = homeConsumerTypeEntity.name;
      setState(() {
        merchantName = name;
        Global.prefs.setString(Global.merchantName, merchantName);
        Global.prefs.setString(Global.phone, homeConsumerTypeEntity.phone);
        Global.prefs.setString(Global.url_avatar, homeConsumerTypeEntity.url);
      });
    }).whenComplete(() => LoadingUtil.hideLoading(context));
  }

  void _getQRCode() {
    ApiInterface.getQRCode().then((value) {
      QrcodeEntity qrcodeEntity = JsonConvert.fromJsonAsT<QrcodeEntity>(value);
      String qrcode = qrcodeEntity.jwt;
      print('身份码：$qrcode');
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) {
            return QrDialog(
              qrContent: qrcode,
              name: merchantName,
            );
          });
    });
  }

  void _scanCodeCallback(String scanResult) {
    ApiInterface.scanCode(scanResult).then((value) {
      QrcodeScanEntity qrcodeScanEntity =
          JsonConvert.fromJsonAsT<QrcodeScanEntity>(value);
      String subjectNo = qrcodeScanEntity.subjectNo;
      showToast(subjectNo);
    });
  }
}
